# 作者：詹广权
# 版权所有：http://www.cdsjcc.cn/xgj
# 说明：贴图穿透插件 - 简化版
# 功能：开启后可直接穿透群组和组件给内部面贴图

require 'sketchup.rb'

module TTCT
  # 贴图穿透功能模块
  module TT
    # 全局变量，记录功能是否激活
    @active = false
    @tool_instance = nil
    
    # 贴图穿透工具类
    class PenetrateTextureEditorTool
      def initialize
        @model = Sketchup.active_model
        @view = @model.active_view
        @cursor_id = nil
        @ip = Sketchup::InputPoint.new
        
        # 预览相关的状态变量
        @hovered_face = nil
        @preview_enabled = true
        @hover_path = nil
        @hover_transformation = nil
        
        # 使用默认光标
         @cursor_id = nil
      end
      
      def activate
        Sketchup.status_text = "贴图穿透模式：已激活 - 点击即可穿透群组和组件进行贴图（按P键切换预览模式）"
        @preview_enabled = true
      end
      
      def deactivate(view)
        view.invalidate
      end
      
      def onLButtonDown(flags, x, y, view)
        process_click(x, y, view)
      end
      
      def process_click(x, y, view)
        material = Sketchup.active_model.materials.current
        return false unless material
        
        ph = view.pick_helper
        pick_radius = 3
        ph.do_pick(x, y, pick_radius, true)
        
        face = nil
        best_depth = Float::INFINITY
        min_face_area = 0.5
        
        count = ph.count
        if count > 0
          count.times do |i|
            depth = ph.depth_at(i)
            entity = ph.leaf_at(i)
            
            if entity.is_a?(Sketchup::Face) && depth < Float::INFINITY
              face_area = entity.area
              
              if face.nil? || (depth < best_depth && face_area >= min_face_area)
                face = entity
                best_depth = depth
                @hover_path = ph.path_at(i)
                @hover_transformation = ph.transformation_at(i)
              end
            end
          end
        end
        
        if face
          begin
            @model.start_operation("贴图穿透", true)
            
            # 应用材质到面
            face.material = material
            
            @model.commit_operation
            
            # 刷新视图
            view.invalidate
            
            puts "贴图穿透：成功应用材质 '#{material.display_name}' 到面"
            return true
          rescue => e
            @model.abort_operation
            puts "贴图穿透：应用材质失败 - #{e.message}"
            return false
          end
        else
          puts "贴图穿透：未找到有效的面"
          return false
        end
      end
      
      def onMouseMove(flags, x, y, view)
        return unless @preview_enabled
        
        ph = view.pick_helper
        ph.do_pick(x, y, 3, true)
        
        old_face = @hovered_face
        @hovered_face = nil
        @hover_path = nil
        @hover_transformation = nil
        
        count = ph.count
        if count > 0
          count.times do |i|
            entity = ph.leaf_at(i)
            if entity.is_a?(Sketchup::Face)
              @hovered_face = entity
              @hover_path = ph.path_at(i)
              @hover_transformation = ph.transformation_at(i)
              break
            end
          end
        end
        
        if @hovered_face != old_face
          view.invalidate
        end
      end
      
      def draw(view)
        return unless @preview_enabled && @hovered_face
        
        begin
          # 绘制高亮边框
          view.line_width = 3
          view.drawing_color = [255, 0, 0, 128]
          
          # 获取面的边界
          edges = @hovered_face.edges
          
          edges.each do |edge|
            start_pt = edge.start.position
            end_pt = edge.end.position
            
            # 如果有变换矩阵，应用变换
            if @hover_transformation
              start_pt = start_pt.transform(@hover_transformation)
              end_pt = end_pt.transform(@hover_transformation)
            end
            
            view.draw_line(start_pt, end_pt)
          end
        rescue => e
          puts "贴图穿透：绘制预览出错 - #{e.message}"
        end
      end
      
      def onKeyDown(key, repeat, flags, view)
        case key
        when 112, 80  # P键或p键
          @preview_enabled = !@preview_enabled
          status = @preview_enabled ? "开启" : "关闭"
          puts "贴图穿透：预览模式已#{status}"
          Sketchup.status_text = "贴图穿透模式：已激活 - 预览模式已#{status}（按P键切换预览模式）"
          view.invalidate
        when 27  # ESC键
          TTCT::TT.deactivate
        end
      end
      
      def getMenu(menu)
        menu.add_item("退出贴图穿透模式") { TTCT::TT.deactivate }
        menu.add_separator
        preview_text = @preview_enabled ? "关闭预览模式" : "开启预览模式"
        menu.add_item(preview_text) do
          @preview_enabled = !@preview_enabled
          view = Sketchup.active_model.active_view
          view.invalidate
        end
      end
    end
    
    # 激活贴图穿透模式
    def self.activate
      return if @active
      
      @tool_instance = PenetrateTextureEditorTool.new
      Sketchup.active_model.select_tool(@tool_instance)
      @active = true
      puts "贴图穿透：模式已激活"
    end
    
    # 关闭贴图穿透模式
    def self.deactivate
      return unless @active
      
      Sketchup.active_model.select_tool(nil)
      @active = false
      @tool_instance = nil
      puts "贴图穿透：模式已关闭"
      Sketchup.status_text = "贴图穿透：模式已关闭"
    end
    
    # 切换贴图穿透模式
    def self.toggle
      # 先关闭模式（如果已激活）
      if @active
        deactivate
      end
      
      # 然后激活模式
      activate
    end
    
    # 检查是否激活
    def self.active?
      @active
    end
  end
  
  # 创建菜单
  def self.create_menu
    menu = UI.menu("Plugins")
    submenu = menu.add_submenu("贴图穿透")
    submenu.add_item("贴图穿透") { TTCT::TT.toggle }
  end
  
  # 创建工具栏
  def self.create_toolbar
    toolbar = UI::Toolbar.new("贴图穿透")
    
    cmd_texture = UI::Command.new("贴图穿透") { TTCT::TT.toggle }
    cmd_texture.tooltip = "贴图穿透"
    cmd_texture.status_bar_text = "点击切换贴图穿透模式"
    
    # 设置工具栏图标
    icon_path = File.join(File.dirname(__FILE__), "ttcc", "tt.png")
    if File.exist?(icon_path)
      cmd_texture.small_icon = icon_path
      cmd_texture.large_icon = icon_path
    end
    
    toolbar.add_item(cmd_texture)
    toolbar.show
    
    puts "贴图穿透：工具栏已创建"
  end
end

# 注册扩展
if !defined?(@ttct_extension_loaded)
  extension = SketchupExtension.new("贴图穿透", File.join(File.dirname(__FILE__), "ttct.rb"))
  extension.description = "允许直接穿透群组和组件进行贴图操作的工具"
  extension.version = "1.0.1"
  extension.creator = "詹广权"
  extension.copyright = "http://www.cdsjcc.cn/xgj"
  
  Sketchup.register_extension(extension, true)
  @ttct_extension_loaded = true
end

# 初始化插件
if !defined?(@ttct_initialized)
  TTCT.create_menu
  TTCT.create_toolbar
  @ttct_initialized = true
  puts "贴图穿透插件已加载完成"
end